package org.hepeng.workx.spring.web.response;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

/**
 * @author he peng
 */

@Aspect
public class ResponseEntityReturnProxy {

    @Around("@within(org.hepeng.workx.spring.web.response.ReturnResponseEntity)")
    public Object returnResponseEntity(ProceedingJoinPoint pjp) throws Throwable {

        Object obj = pjp.proceed(pjp.getArgs());
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        ReturnResponseEntity returnResponseEntity = MethodUtils.getAnnotation(
                signature.getMethod(), ReturnResponseEntity.class,
                true, true);
        String httpStatusName = returnResponseEntity.value();
        HttpStatus httpStatus = HttpStatus.OK;
        Object val = FieldUtils.readDeclaredField(obj, httpStatusName);
        if (String.class.isAssignableFrom(val.getClass())) {
            httpStatus = HttpStatus.valueOf(StringUtils.upperCase((String)val));
        } else if (Integer.class.isAssignableFrom(val.getClass())) {
            httpStatus = HttpStatus.resolve((int) val);
        } else if (HttpStatus.class.isAssignableFrom(val.getClass())) {
            httpStatus = (HttpStatus) val;
        }
        return ResponseEntity.status(httpStatus).body(obj);
    }
}
